package com.supermap.gwfs.datashare.of.service;

import java.awt.geom.Rectangle2D;
import java.io.IOException;

import org.springframework.stereotype.Service;
import ucar.nc2.NetcdfFile;

import com.supermap.gwfs.datashare.entity.GridData;
import com.supermap.gwfs.datashare.util.DataFormatUtil;
import com.supermap.gwfs.datashare.util.Logger;
import com.supermap.gwfs.datashare.util.NetCDFAllUtil;

/**  
 * @Description: TODO
 * @author zhoujian
 * @date 2017-6-19
 * @version V1.0 
 */
@Service
public class NetcdfService
{
	private Logger logger = Logger.getLogger(this.getClass());
	
	/**
	 * 
	 * @Description: 读取Netcdf文件数据
	 * @return GridData
	 * @throws
	 */
	public GridData getGridDataFromNetcdf(String filePath, String element)
	{
		NetcdfFile ncFile = null;
		GridData gridData = null;
		try
		{
			ncFile = NetcdfFile.open(filePath);
			
			int rows = NetCDFAllUtil.getRows(ncFile);	//行数
			int cols = NetCDFAllUtil.getCols(ncFile);	//列数
			String unit = NetCDFAllUtil.getUnit(element, ncFile);//单位
			int level = NetCDFAllUtil.getLevel(ncFile);//层次
			float[] values = NetCDFAllUtil.getValues(element, ncFile);//数据
			
			float[][] valuesD2 = DataFormatUtil.arrayD1ToD2(values, rows, cols);
			
			Rectangle2D rectangle = NetCDFAllUtil.getGeoBounds(ncFile);//范围
			//计算分辨率
			float lonResolution = DataFormatUtil.formatFloat(rectangle.getWidth()  / (cols-1), 3);
			float latResolution = DataFormatUtil.formatFloat(rectangle.getHeight() / (rows-1), 3);
			
			float startLon = (float)rectangle.getX();
			float startLat = (float)rectangle.getY();
			float endLon = (float)(rectangle.getX() + rectangle.getWidth());
			float endLat = (float)(rectangle.getY() + rectangle.getHeight());
			
			//从文件名中裁切出时效
			int valid = 0 ;
			if (filePath.lastIndexOf("_") != -1 && filePath.lastIndexOf(".") != -1)
			{
				valid = Integer.valueOf((String) filePath.subSequence(filePath.lastIndexOf("_") + 1, filePath.lastIndexOf(".")));
				
			}
			
			
			gridData = new GridData(element, valid,rows, cols, unit, level, startLon , startLat , endLon , endLat, lonResolution, latResolution, valuesD2);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			logger.error("Analysis netcdf file exception , this exception is : " + e);
		}
		finally
		{
			try
			{
				if (ncFile != null)
				{
					ncFile.close();
				}
			}
			catch (IOException e)
			{
				logger.error("closed netcdf object exception , this exception is : " + e);
			}
		}
		return gridData;
	}
}
